package com.airlines.base.config.datasource;

import javax.sql.DataSource;

import org.apache.ibatis.session.SqlSessionFactory;
import org.mybatis.spring.SqlSessionFactoryBean;
import org.mybatis.spring.SqlSessionTemplate;
import org.mybatis.spring.annotation.MapperScan;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.boot.autoconfigure.condition.ConditionalOnProperty;
import org.springframework.boot.context.properties.ConfigurationProperties;
import org.springframework.boot.jdbc.DataSourceBuilder;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.core.io.support.PathMatchingResourcePatternResolver;
import org.springframework.jdbc.datasource.DataSourceTransactionManager;

/**
 * @author xxxx
 * @date 2018年3月15日
 * @description 数据源2的配置
 * @ConditionalOnProperty 用来控制是否创建该DataSource，即配置文件中有包含spring.datasource.second.url ,username,password时，
 */
//@ConditionalOnProperty(prefix = "spring.datasource."+FocMysqlDataSourceConfig.DATA_SOURCE_NAME ,name = {"url","username","password"})
@Configuration
@MapperScan(basePackages = {FocMysqlDataSourceConfig.BASE_PACKAGE}, sqlSessionTemplateRef = FocMysqlDataSourceConfig.DATA_SOURCE_NAME+"SqlSessionTemplate")
public class FocMysqlDataSourceConfig {
	
	public FocMysqlDataSourceConfig() {
		
	}
	
	//如果新增或者修改数据源，更新配置以下3个常量即可
	public static final String DATA_SOURCE_NAME="foc-mysql";
	public static final String BASE_PACKAGE="com.airlines.crewassignment.daofocmysql";
	public static final String MAPPER_PACKAGE="classpath*:mybatis/mapperfocmysql/*/*.xml";
	public static final String TRANSACTION_MANAGER=DATA_SOURCE_NAME+"TransactionManager";
	
	@Bean(name = DATA_SOURCE_NAME+"DataSource")
	@ConfigurationProperties(prefix = "spring.datasource."+DATA_SOURCE_NAME)
	public DataSource dataSource() {
		return DataSourceBuilder.create().build();
	}

	@Bean(name = DATA_SOURCE_NAME+"SqlSessionFactory")
	public SqlSessionFactory sqlSessionFactory(@Qualifier(DATA_SOURCE_NAME+"DataSource") DataSource dataSource)
			throws Exception {
		SqlSessionFactoryBean bean = new SqlSessionFactoryBean();
		bean.setDataSource(dataSource);
		bean.setMapperLocations(new PathMatchingResourcePatternResolver().getResources(MAPPER_PACKAGE));
		return bean.getObject();
	}

	@Bean(name =TRANSACTION_MANAGER)
	public DataSourceTransactionManager transactionManager(@Qualifier(DATA_SOURCE_NAME+"DataSource") DataSource dataSource) {
		return new DataSourceTransactionManager(dataSource);
	}

	@Bean(name = DATA_SOURCE_NAME+"SqlSessionTemplate")
	public SqlSessionTemplate sqlSessionTemplate(
			@Qualifier(DATA_SOURCE_NAME+"SqlSessionFactory") SqlSessionFactory sqlSessionFactory) throws Exception {
		return new SqlSessionTemplate(sqlSessionFactory);
	}
}
